﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbSharp.Framework.Storage.IO;
using System.IO;
using System.Xml.Linq;
using DbSharp.Utils.Db;

namespace DbSharp.Framework.Storage.Export
{
    class XmlExportWriter : IExportWriter
    {
        private void ExportScalar(string xmlFile, XElement dataRootElement)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<resultset>");
            //get data value xml section
            sb.AppendLine(dataRootElement.ToString());
            sb.AppendLine("</resultset>");
 
            File.WriteAllText(xmlFile, sb.ToString(), Encoding.UTF8);
        }


        private void ExportRecordset(string xmlFile, IEnumerable<XElement> listRecordElement, long exportRecordCount)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<resultset>");
            //get list of row section
            RecordsetXElmtTextWriter writer = new RecordsetXElmtTextWriter(listRecordElement, true, exportRecordCount);
            sb.AppendLine(writer.StringBuilder.ToString());
            sb.AppendLine("</resultset>");

            File.WriteAllText(xmlFile, sb.ToString(), Encoding.UTF8);
        }

 


        #region IExportWriter Members

        public void Export(string fileName, object obj, long exportRecordCount)
        {

            if (ExportWriterHelper.IsRecordset(obj))
            {
                ExportRecordset(fileName, (IEnumerable<XElement>)obj, exportRecordCount);
            }
            else
            {
                ExportScalar(fileName, (XElement)obj);
            }
        }

        #endregion
    }
}
